//
//  NoticeSetViewController.swift
//  MyTest
//
//  Created by guanzhongwang on 2021/5/7.
//

import UIKit

class NoticeSetViewController: CommonViewController {
    private let tableView = UITableView.init(frame: CGRect.zero, style: .grouped)
    private var dataList:Array<SessionItem> = []
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.title = "推送通知设置"
        self.view.addSubview(tableView)
        tableView.snp.makeConstraints({
            $0.edges.equalToSuperview()
        })
        tableView.separatorColor = Separator_COLOR
        tableView.backgroundColor = BACKGROUND_COLOR

        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(SetItemArrowCell.self, forCellReuseIdentifier: "SettingArrowCell")
        tableView.register(SetItemSwitchCell.self, forCellReuseIdentifier: "SettingSwitchCell")
        tableView.estimatedSectionHeaderHeight = 0
        tableView.estimatedSectionFooterHeight = 0
        tableView.rowHeight = 44.0
        
        dataList.append(SessionItem([SetItemModel.init(type: .Switch, title: "推送通知设置",subTitle: "有重要资讯和互动消息时通知我")]))
        dataList.append(SessionItem([SetItemModel.init(type: .Switch, title: "重大新闻通知")],title: "重大新闻"))
        dataList.append(SessionItem([SetItemModel.init(type: .Switch, title: "收到评论或回复"),
                                     SetItemModel.init(type: .Switch, title: "收到点赞"),
                                     SetItemModel.init(type: .Switch, title: "转发")],title: "互动"))

        dataList.append(SessionItem([SetItemModel.init(type: .Switch, title: "获得新粉丝"),
                                     SetItemModel.init(type: .Switch, title: "关注的人发布了新内容")],title: "关注"))
        dataList.append(SessionItem([SetItemModel.init(type: .Switch, title: "预约提醒",subTitle: "影视/直播/赛事等"),
                                     SetItemModel.init(type: .Switch, title: "订阅提醒",subTitle: "小说/精品课等")],title: "预约和订阅"))
        dataList.append(SessionItem([SetItemModel.init(type: .Switch, title: "消息免打扰",isOn: false)
                                     ],title: "免打扰"))
    }
    override func viewDidDisappear(_ animated: Bool) {
        // 取消cell的代理，不然controller无法释放
        for (_,view) in tableView.subviews.enumerated() {
            if view.isKind(of: SetItemSwitchCell.self) {
                let cell = view as! SetItemSwitchCell
                cell.delegate = nil
            }
        }
    }
}
fileprivate struct SessionItem {
     var title:String = ""
     var list:[SetItemModel] = []
    init(_ list:[SetItemModel],title:String="") {
        self.list=list
        self.title = title
    }
}
extension NoticeSetViewController:UITableViewDelegate{
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        guard dataList[section].title == "" else {
            return 40.0
        }
        return 10.0
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == dataList.count - 1 {
            return 30.0
        }
        return 0.001
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let item = dataList[indexPath.section].list[indexPath.row]
        if(item.subTitle == ""){
            return 44.0
        }else{
            return 60.0
        }
    }
   
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        SystemLog("didSelectRowAt")
        tableView.deselectRow(at: indexPath, animated: false)
        if indexPath.section == dataList.count-1 && dataList[indexPath.section].list.count == 2 {
            let picker = UIDatePicker()
            picker.calendar = .current
            picker.backgroundColor = .white
            picker.datePickerMode = .time
            self.view.addSubview(picker)
            picker.snp.makeConstraints({
                $0.left.right.bottom.equalTo(0)
                $0.height.equalTo(300)
            })
        }
    }
    
}
extension NoticeSetViewController:UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return dataList[section].list.count
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return dataList.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let item = dataList[indexPath.section].list[indexPath.row]
        if item.type == .Arrow {
            let cell = tableView.dequeueReusableCell(withIdentifier: "SettingArrowCell", for: indexPath) as? SetItemArrowCell
            cell?.binding(item)
            return cell!
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: "SettingSwitchCell", for: indexPath) as? SetItemSwitchCell
            cell?.binding(item,indexPath:indexPath)
            cell?.delegate = self
            if indexPath.section != 0{
                cell?.isUserInteractionEnabled = dataList[0].list[0].isOn
            }
            return cell!
        }
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let item = dataList[section]
        if(item.title != ""){
            let view = UIView()
            let titleL = UILabel()
            titleL.textColor = B999_TITLE_COLOR
            titleL.text = item.title
            titleL.font = Font_Size_12
            view.addSubview(titleL)
            titleL.snp.makeConstraints({
                $0.centerY.equalToSuperview().offset(7)
                $0.left.equalToSuperview().inset(15)
            })
            return view
        }
        return nil
    }
}
extension NoticeSetViewController:SetItemCellDelegate{
    func swithcValueChanged(_ indexPath:IndexPath) {
        var  item = dataList[indexPath.section].list[indexPath.row]
        if indexPath.section == 0 {
            item.isOn = !item.isOn
            var color = B000_COLOR
            if !item.isOn {
                color = B999_TITLE_COLOR
            }
            dataList = dataList.map({ (session) -> SessionItem in
                return SessionItem(session.list.map { (temp) -> SetItemModel in
                    return SetItemModel.init(type: temp.type, title: temp.title,subTitle: temp.subTitle,isOn: item.isOn,titleColor: color)
                },title: session.title)
            })
            if item.isOn {
                dataList[0].list[0].subTitleColor = B999_TITLE_COLOR
                dataList[0].list[0].subTitle = "有重要资讯和互动消息时通知我"
            }else{
                dataList[0].list[0].subTitleColor = RED_COLOR
                dataList[0].list[0].subTitle = "你可能错过重要资讯通知,点击开启消息通知"
                dataList[dataList.count-1].list = [dataList[dataList.count-1].list[0]]
            }
            dataList[0].list[0].titleColor = B000_COLOR
            dataList[dataList.count-1].list[0].isOn = false
        }else{
            if dataList[0].list[0].isOn == true {
                dataList[indexPath.section].list[indexPath.row].isOn = !item.isOn
                if indexPath.section == dataList.count-1{
                    if item.isOn {
                        dataList[indexPath.section].list = [dataList[indexPath.section].list[0]]
                    }else{
                        dataList[indexPath.section].list = [dataList[indexPath.section].list[0],SetItemModel.init(type: .Arrow, title: "免打扰时间",tip: "00:00-06:00")]
                    }
                }
            }
        }
        tableView.reloadData()
    }
}
